<?php
if(isset($_SESSION['user_token']))
{
}
else
{
	// create unique token
	$form_token = uniqid();

	// commit token to session
	$_SESSION['user_token'] = $form_token;
}
if(isset($_POST['user_token']))
{
	//We check if the token of the page and session match!
	if($_POST['user_token'] == $_SESSION['user_token']) {
        $username = $db_mysql->db_input(setVar("username",""));     
        $password = $db_mysql->db_input(setVar("password",""));     
		if($username == "" || $password == "")
		{
			$message = 'Please input valid username or password!';
		}
		else
		{
			$password = md5($password);
			$sql = "select * from users where activate = 1 and username = '$username' and password = '$password'";
			$rows = $db_mysql->query($sql);
			$row = $db_mysql->fetch_array($rows);
			if($row)
			{
				$arr = array('user_id'=>$row["user_id"], 'full_name'=>$row["full_name"], 'email'=>$row["email"],'password'=>$row["password"],'user_type'=>$row["user_type"]);
				$_SESSION[LOGIN_SESSION_NAME] = $arr;
				update_last_login($row["user_id"]);
				
				unset($_SESSION['user_token']);
				redirectPage("index.php?module=games_list");
			}
			else
			{
				$message = 'Invalid username or password!';
			}
		}
	} else {
		echo 'Your request has expired, please go back and resubmit!';
		unset($_SESSION['user_token']);
		exit();
	}
}
?>
<?php include('includes/header.php'); ?>
<script>
	

$(document).keypress(function(e) {
  if(e.which == 13) {
    // enter pressed
	document.frmLogin.submit();
  }
});


</script>
<div id="content">
	<div id="stage-2" style="display:block">
		
		<p><small><?= isset($message) ? $message : ""?></small></p>
		
	    <div id="freeloader" class="login-admin">
	        <h2>Login</h2>
	        <form name="frmLogin" action="" method="post">
	            <input type="hidden" name="user_token" value="<?php echo  $_SESSION['user_token'];  ?>" />
	            <label for="username">User name:</label>
				<div class="clear"></div>
	            <input type="text" name="username" value="" id="username">
	            <label for="password">Password:</label>
				<div class="clear"></div>
	            <input type="password" name="password" value="" id="password">
	        
	            <a href="javascript:;" onclick="document.frmLogin.submit();" class="signup">Login</a>
	        </form>
	    </div>
	    <div class="clear"></div>
	</div>
</div>
